import React, { useEffect, useRef, useState } from "react";
import { SearchBar, NavBar, Toast } from "antd-mobile";
import { SearchBarRef } from "antd-mobile/es/components/search-bar";

import styles from "./styles.module.scss";
import { useSearchs } from "hooks/todo/useSearchs";
import { useSearchTodo } from "hooks/todo/useSearchTodo";
import { EmptyWrapper } from "components/EmptyWrapper";
import { TodoItem } from "components/TodoItem";
import { useTodos } from "hooks/todo/useTodos";

export default function SearchContent() {
  const params = new URLSearchParams(window.location.search);
  const [searchContent, setSearchContent] = useState(params.get("q")!);
  const searchRef = useRef<SearchBarRef>(null);
  const { createSearch } = useSearchs();

  const { todos, searchTodos } = useSearchTodo();
  const {
    todoMsg,
    deleteOneTodo,
    updateTodoContent,
    toggleTodoFinish,
    toggleTodoImportant,
  } = useTodos();
  useEffect(() => {
    if (todoMsg) {
      Toast.show(todoMsg);
    }
  }, [todoMsg]);

  useEffect(() => {
    if (searchContent) {
      searchTodos(searchContent);
    }
  }, [searchContent, searchTodos]);

  const searchHandle = () => {
    createSearch(searchContent.trim());
    console.log("搜索内容: " + searchContent);
    searchTodos(searchContent);
  };

  return (
    <div>
      <div className={styles.header}>
        <NavBar
          onBack={() => {
            window.history.back();
          }}
          style={{
            "--height": "50px",
            "--border-bottom": "1px solid #eee",
          }}
        >
          <SearchBar
            ref={searchRef}
            placeholder="搜索"
            showCancelButton={() => true}
            value={searchContent}
            onChange={(value) => {
              setSearchContent(value);
            }}
            onSearch={() => {
              searchHandle();
            }}
            style={{
              "--border-radius": "12px",
              "--background": "#EDEDED",
            }}
          />
        </NavBar>
      </div>
      {todos.length === 0 ? (
        <EmptyWrapper desc="暂无搜索结果"></EmptyWrapper>
      ) : (
        <div className={styles.list}>
          {todos.map((todo) => (
            <TodoItem
              key={todo.id}
              todo={todo}
              deleteOneTodo={deleteOneTodo}
              updateTodoContent={updateTodoContent}
              toggleTodoFinish={toggleTodoFinish}
              toggleTodoImportant={toggleTodoImportant}
            />
          ))}
        </div>
      )}
    </div>
  );
}
